package com.digitalchina.lxnsy.activity.old;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;

import com.afollestad.materialdialogs.MaterialDialog;
import com.apkfuns.logutils.LogUtils;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.api.BusinessAccount;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.Constant;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.constant.TIME;
import com.digitalchina.lxnsy.entity.PointVO;
import com.digitalchina.lxnsy.entity.UserVO;
import com.digitalchina.lxnsy.toolkit.ActivityTaskManager;
import com.digitalchina.lxnsy.toolkit.DateStyle;
import com.digitalchina.lxnsy.toolkit.DateUtil;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.GotoUtil;
import com.digitalchina.lxnsy.toolkit.RegexpUtil;
import com.digitalchina.lxnsy.toolkit.StringUtil;
import com.digitalchina.lxnsy.toolkit.Utils;
import com.digitalchina.lxnsy.widget.EditTextWithClear;
import com.digitalchina.lxnsy.xml.RongCloudXML;
import com.digitalchina.lxnsy.xml.UserXML;

import java.io.Serializable;
import java.util.List;
import java.util.Set;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

import static com.digitalchina.lxnsy.constant.Constant.MSG_SET_ALIAS;


/**
 * ================================================
 * 项目名称：bigdata
 * 类描述：
 * 包名：com.digitalchina.bigdata.activity
 * 创建人：白彦东
 * 创建时间：2016/12/19 19:25
 * 修改备注：
 * ================================================
 */

public class LoginCodeActivity extends BaseActivity {


    @Bind(R.id.login_code_et_mobile)
    EditTextWithClear loginCodeEtMobile;
    @Bind(R.id.login_code_et_auth_code)
    EditTextWithClear loginCodeEtAuthCode;
    @Bind(R.id.login_code_bt_auth_code)
    Button loginCodeBtAuthCode;
    @Bind(R.id.login_code_bt_login)
    Button loginCodeBtLogin;

    private UserVO userVO;

    @Override
    public void setLayout() {
        setTitle("验证码登录");
//        setRightText("注册");
        setContentLayout(R.layout.activity_login_code);
    }

    @Override
    public void initMember() {

    }

    @Override
    public void addListener() {

    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                dismissDialog();
                switch (msg.what) {
                    case MSG.MSG_LOGIN_SUCCESS:   // 登录成功
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_LOGIN_FAILED:
                        showToast(msg.obj.toString());
                        break;
                    case MSG_SET_ALIAS:
                        LogUtils.e("Set alias in handler.");
                        JPushInterface.setAliasAndTags(getApplicationContext(), (String) msg.obj, null, mAliasCallback);
                        break;
                    case MSG.MSG_GET_USER_RC_TOKEN_SUCCESS:
                        getTokenSuccess(msg.obj);
                        break;
                    case MSG.MSG_GET_USER_RC_TOKEN_FIELD:
                        showToast(msg.obj.toString());
                        break;
                    case MSG.MSG_SEND_VERIFY_CODE_TIP:
                        if (isFinishing())
                            return;
                        loginCodeBtAuthCode.setClickable(false);
                        loginCodeBtAuthCode.setTextColor(Color.parseColor("#b3b3b3"));
                        loginCodeBtAuthCode.setText(String.valueOf(msg.obj));
                        loginCodeBtAuthCode.setBackgroundResource(R.drawable.shape_bt_auth_code_disable);
                        break;
                    case MSG.MSG_SEND_VERIFY_CODE_END:
                        if (isFinishing())
                            return;
                        loginCodeBtAuthCode.setClickable(true);
                        loginCodeBtAuthCode.setTextColor(getResources().getColor(R.color.app_color));
                        loginCodeBtAuthCode.setText("发送验证码");
                        loginCodeBtAuthCode.setBackgroundResource(R.drawable.shape_rect_app_color);
                        break;
                    case MSG.MSG_USER_LOGIN_CODE_SEND_SUCCESS: // 发送验证码成功
                        Utils.startForbitSendVerifyCode(LoginCodeActivity.this,
                                mHandler, TIME.SEND_CHECKCODE_TIME, null);
                        break;
                    case MSG.MSG_USER_LOGIN_CODE_SEND_FIELD:
                        showToast(msg.obj.toString());
                        break;
                }
            }

        };
    }

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {

        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    LogUtils.e(logs);
                    break;

                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    LogUtils.e(logs);
                    if (Utils.isConnected(getApplicationContext())) {
                        mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
                    } else {
                        LogUtils.e("No network");
                    }
                    break;

                default:
                    logs = "Failed with errorCode = " + code;
                    LogUtils.e(logs);
            }

        }

    };

    /**
     * 获取token成功 保存用户信息并跳转
     */
    private void getTokenSuccess(Object obj) {

        LogUtils.e("获取服务端Token成功,已保存到XML");

        // 解析获取到的token
        String token = FastJsonUtil.getString(obj.toString(), "data");
        RongCloudXML.setUserToken(LoginCodeActivity.this, UserXML.getUserId(this), token);

    }


    @Override
    public void callBack(Object object) {

        userVO = FastJsonUtil.getBean(object.toString(), "body", "", UserVO.class);
        userVO.setLoginName(StringUtil.getEditText(loginCodeEtMobile));

        if (!StringUtil.isStrEmpty(userVO.getHasSettingRole()) && userVO.getHasSettingRole().equals("0")) {
            GotoUtil.gotoActivity(LoginCodeActivity.this, LoginSelectTypeActivity.class, true, "userVO", userVO);
            return;
        }

        List<PointVO> pointVOList = FastJsonUtil.getListBean(object.toString(), "body", "rewardPointDetailList", PointVO.class);


        if (userVO == null) {
            showToast("登录失败：用户信息异常");
            return;
        }

        if (!userVO.getUserType().equals(Constant.USER_TYPE_PERSON)
                && !userVO.getUserType().equals(Constant.USER_TYPE_EXPERT)) { //除了个人用户和专家 其他无登录权限
            new MaterialDialog.Builder(this)
                    .title("提示")
                    .content("对不起，该用户没有权限！")
                    .positiveText("确定")
                    .show();
            return;
        }

        showToast("登录成功");


        //个人信息存储
        UserXML.setUserVO(this, userVO);
        setAlias(userVO.getUseraccid().replace("-", ""));



        // 注册为个人用户
        if (userVO.getUserType().equals(Constant.USER_TYPE_PERSON) || (userVO.getUserType().equals(Constant.USER_TYPE_EXPERT)) && !userVO.getIsAudit().equals("3")) {


            UserXML.setTodayLogin(LoginCodeActivity.this, DateUtil.getCurrentDate(DateStyle.YYYY_MM_DD));
            UserXML.setLoginStatus(LoginCodeActivity.this, UserXML.USER_IS_LOGIN_VALUE);


            if (ActivityTaskManager.getInstance().size() > 1) {
                Intent i = new Intent();
                Bundle bundle = new Bundle();
                bundle.putSerializable("pointVOList", (Serializable) pointVOList);
                i.putExtras(bundle);
                setResult(1, i);
                finish();
            } else {
                GotoUtil.gotoActivity(LoginCodeActivity.this, MainActivity.class, true, "pointVOList", pointVOList);
            }
        } else {
            // 注册为专家用户
            GotoUtil.gotoActivity(LoginCodeActivity.this, SaveExpertInfoActivity.class, true);
        }
    }

    private void setAlias(String alias) {
        LogUtils.e(alias);
        if (TextUtils.isEmpty(alias)) {
            LogUtils.e("alias is empty");
            return;
        }
        if (!Utils.isValidTagAndAlias(alias)) {
            LogUtils.e("alias is not valid");
            return;
        }

        //调用JPush API设置Alias
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, alias));
    }

    @Override
    public void rightOnClick() {
        GotoUtil.gotoActivity(this, RegisterTypeSelectActivity.class, true);
    }

    @OnClick({R.id.login_code_bt_login, R.id.login_code_bt_auth_code, R.id.login_code_tv_to_psw_login})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.login_code_bt_login:
                login(); // 登录
                break;
            case R.id.login_code_bt_auth_code:
                getAuthCode();
                break;
            case R.id.login_code_tv_to_psw_login: // 跳转到密码登录
                GotoUtil.gotoActivity(LoginCodeActivity.this, LoginActivity.class, true);
                break;
        }
    }

    /**
     * 获取验证码
     */
    private void getAuthCode() {
        String pStrMobile = loginCodeEtMobile.getText().toString();

        if (StringUtil.isStrEmpty(pStrMobile)) {
            showToast("手机号不能为空");
            return;
        }

        if (!RegexpUtil.isRegexpValidate(pStrMobile, RegexpUtil.MOBILE_REGEXP)) {
            showToast("请输入合法手机号");
            return;
        }


        BusinessAccount.sendLoginVerifyCode(this, pStrMobile, mHandler);

    }

    /**
     * 登录
     */
    private void login() {


        String pStrMobile = loginCodeEtMobile.getText().toString();
        String pStrCode = loginCodeEtAuthCode.getText().toString();

        if (StringUtil.isStrEmpty(pStrMobile)) {
            showToast("手机号不能为空");
            return;
        }

        if (!RegexpUtil.isRegexpValidate(pStrMobile, RegexpUtil.MOBILE_REGEXP)) {
            showToast("请输入合法手机号");
            return;
        }

        if (StringUtil.isStrEmpty(pStrCode)) {
            showToast("验证码不能为空");
            return;
        }

        BusinessAccount.loginByPhone(this, pStrMobile, pStrCode, mHandler);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }



    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            if (ActivityTaskManager.getInstance().size() == 1) {
                GotoUtil.gotoActivity(LoginCodeActivity.this, MainActivity.class, true);
            } else
                finish();
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

}


